package rise.ui;

import rise.comunity.Community;
import rise.comunity.Status;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class UserAdapter extends ArrayAdapter<String> {
	private static final String oneIncomingMessage = "Hai un nuovo messaggio.";
	private static final String mulitpleMessagesPre = "Hai ";
	private static final String mulitpleMessagesPost = " nuovi messaggi.";

	public UserAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
	}

	@Override
	public String getItem(int position) {
		Community community = Community.obtainCommunity();
		return community.getUserAt(position);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.user_row, null);
		}

		String username = this.getItem(position);
		
		Community community = Community.obtainCommunity();
		Status status = community.getUserStatus(username);

		TextView messageSender = (TextView) convertView
				.findViewById(R.id.username);
		TextView conversationSizeMessage = (TextView) convertView
				.findViewById(R.id.conversation_size);

		messageSender.setText(username);
		this.setCardinalityMessage(username, community, conversationSizeMessage);
		this.setStatusImage(convertView, status);

		return convertView;
	}

	private void setStatusImage(View convertView, Status status) {
		ImageView statusImage = (ImageView) convertView
				.findViewById(R.id.userStatus);

		if (status == Status.OFFLINE) {
			statusImage.setImageResource(R.drawable.invisible);
		} else if (status == Status.BUSY) {
			statusImage.setImageResource(R.drawable.busy);
		} else {
			statusImage.setImageResource(R.drawable.online);
		}
	}

	private void setCardinalityMessage(String username, Community community,
			TextView conversationSizeMessage) {
		int conversationSize = community.getMessagesCardinalityFrom(username);

		if (conversationSize == 0)
			conversationSizeMessage.setText(R.string.noMessage);
		else if (conversationSize == 1)
			conversationSizeMessage.setText(oneIncomingMessage);
		else
			conversationSizeMessage.setText(mulitpleMessagesPre
					+ conversationSize + mulitpleMessagesPost);
	}

}